<template>
  <div class="main">
    <div class="content">
      <div class="content_left">
        <img src="../assets/logo.png" alt="" />
        <div>欢迎！</div>
        <div>智学商城-后台管理系统</div>
      </div>
      <div class="content_right">
        <div class="content_right_title">登录</div>
        <div class="demo-input-size">
          <!-- 表单组件 -->
          <el-form ref="ruleFormRef" :model="ruleForm" status-icon :rules="rules" class="demo-ruleForm">
            <el-form-item prop="username">
              <el-input v-model.trim="ruleForm.username" type="text" autocomplete="off" placeholder="账号"
                :prefix-icon="User" />
            </el-form-item>
            <el-form-item prop="password">
              <el-input v-model.trim="ruleForm.password" type="password" autocomplete="off" placeholder="密码"
                :prefix-icon="Lock" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="submitForm(ruleFormRef)">登录</el-button>
            </el-form-item>
          </el-form>
        </div>
        <!-- <div class="content_right_author">作者：曹老师</div> -->
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import type { FormInstance } from 'element-plus'
import { User, Lock } from '@element-plus/icons-vue'
import { ElMessage } from "element-plus"
import cookie from 'js-cookie'
import router from '@/router'
import { useLoginStore } from "../stores/login"
import { useUserStore } from '@/stores/admin';
import { post } from '@/utils/http'
import { useRoute } from 'vue-router'


// import {login,getInfo} from '@/api/api'

const store = useUserStore();
const route = useRoute()
const loginStore = useLoginStore()

const ruleFormRef = ref<FormInstance>()

// 设置表单验证规则
const validateUsername = (rule: object, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入账号'))
  } else {
    callback()
  }
}
const validatePassword = (rule: object, value: string, callback: any) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    callback()
  }
}

// 表单数据绑定
const ruleForm = reactive({
  username: 'admin',
  password: '123456'
})

// 绑定表单验证规则与验证方式
const rules = reactive({
  username: [{ validator: validateUsername, trigger: 'blur' }],
  password: [{ validator: validatePassword, trigger: 'blur' }]
})

// 通过验证规则后，表单提交登录按钮
const submitForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid) => {
    if (valid) {

      // 接口需要的数据data
      let data = {
        _gp: 'admin',
        _mt: 'login',
        ...ruleForm
      }

      // 接口连调
      post(data).then(res => {         //访问开发服务器
        console.log(res);
        // let { data: token, errmsg, errno } = res.data
        let { data: token ,errno,errmsg } = res
        if (200 === errno) {
          ElMessage.success("登录成功！")

          loginStore.toToken(token)   //将token存储到pinia中
          // 将token写入到cookie中,过期时间为30分钟
          let now_time = new Date()
          now_time.setTime(now_time.getTime() + 1000 * 60 * 30)
          cookie.set('token', token, { expires: now_time })

          return Promise.resolve(token)
        } else {
          return Promise.reject(errmsg)
        }
      }).then((res) => {        //获取用户信息
        const token = res;
        const data = {
          _gp: 'admin',
          _mt: 'info'
        }
        post(data).then((res: any) => {
          console.log(res);
          
          const { data, errno, errmsg } = res;


          if (200 === errno) {
            store.setUser(data.data)

            // 跳回登出的路径
            let back = route.query.back
            if (back) {
              router.replace(back as string)
              return;
            }
            router.replace("/index/home")
          } else {
            return Promise.reject(errmsg)
          }

        })
      }).catch((err) => {
        ElMessage.error(err)
      })


    } else {
      console.log('error submit!')
      return false
    }
  })
}

</script>

<style scoped>
.main {
  width: 100%;
  height: 100%;
  background: url("../assets/bgpic.jpg");
  background-repeat: no-repeat;
  background-size: cover;
  position: relative;
}

.content {
  width: 60%;
  height: 60%;
  background-color: white;
  position: absolute;
  margin: auto;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
}

.content_left {
  width: 40%;
  height: 100%;
  background-color: #005DE9;
  color: white;
  font-size: 1.2rem;
  text-align: center;
  line-height: 200%;
  box-sizing: border-box;
  padding-top: 10%;
  float: left;
}

.content_left img {
  width: 30%;
  border-radius: 50%;
  box-shadow: 0 0 2rem #fff;
}

.content_right {
  width: 60%;
  height: 100%;
  /* background-color: aquamarine; */
  box-sizing: border-box;
  float: right;
  color: #453838d2;
  font-size: 1.2rem;
  text-align: center;
  padding-top: 10%;
  line-height: 4rem;
}


.content_right_author {
  font-size: .8rem;
}

.demo-input-size {
  width: 80%;
  box-sizing: border-box;
  padding-left: 20%;
}
</style>
